package customControls;

import android.annotation.SuppressLint;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import com.example.jaden.washer.R;

import java.util.List;

import dormitory.Dormitory;
import washer.Washer;

import static com.example.jaden.washer.R.drawable.washerusing;

public class WasherAdapter extends ArrayAdapter {
    Washer washer;
    int Position;
    private int resourceId;
    ;
    public  WasherAdapter(@NonNull Context context, int resource, List<Washer> objects) {
        super(context, resource, objects);
        resourceId = resource;
    }
    public class ViewHolder
    {
        TextView number;
        TextView washerID;
        TextView isfree;
    }
    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {

        Position=position;
        //根据position 得到当前子项的Commodity实例
        washer = (Washer) getItem(position);
        ViewHolder viewHolder = null;
        if(convertView==null)
        {
            //Log.d(TAG, "getView: "+position);
            //为当前子项加载指定布局->resourceId
            convertView= LayoutInflater.from(getContext()).inflate(resourceId,parent,false);
            viewHolder=new ViewHolder();
            //获取控件实例
            getInstance(viewHolder,convertView);
            convertView.setTag(viewHolder);
        }
        else {
            viewHolder= (ViewHolder) convertView.getTag();
        }
        //显示控件信息
        showInformation(viewHolder);
        return convertView;
    }

    //获取控件实例
    private void getInstance(ViewHolder viewHolder, View view) {
        viewHolder.number=(TextView)view.findViewById(R.id.textView_number_washerlistviewitem);
        viewHolder.washerID=(TextView)view.findViewById(R.id.textView_washerID_washerlistviewitem);
        viewHolder.isfree=(TextView)view.findViewById(R.id.textView_isfree_washerlistviewitem);

    }
    //显示控件信息
    @SuppressLint("ResourceAsColor")
    private void showInformation(ViewHolder viewHolder) {
        Position+=1;
        viewHolder.number.setText("#"+Position);
        if(washer.isIsFree()) {
            viewHolder.isfree.setText("空闲");
            viewHolder.isfree.setTextColor(R.color.colorPrimary);
            viewHolder.isfree.setCompoundDrawablesWithIntrinsicBounds(getContext().getResources().getDrawable(R.drawable.washmaching),null,null,null);
        }
        else {
            viewHolder.isfree.setText("在使用");
            viewHolder.isfree.setTextColor(R.color.colorred);
            viewHolder.isfree.setCompoundDrawablesWithIntrinsicBounds(getContext().getResources().getDrawable(R.drawable.washerusing),null,null,null);
        }
        viewHolder.washerID.setText("洗衣机ID:"+washer.getWasherID());
    }
}
